<?php

namespace app\api\controller;

use app\api\middleware\Article as MiddlewareArticle;
use app\api\model\ArtCollect;
use app\api\model\Article as ModelArticle;
use app\api\model\Category;
use app\api\model\User;
use app\common\LogService;
use app\common\ScoreLog;
use app\Request;
use think\facade\Db;
use think\facade\Log;

class Article extends Base
{
    protected $middleware = [MiddlewareArticle::class => ['only' => ['add', 'edit']]];
    // 我的文章 | 查看别人的文章 列表
    public function index($id = 0)
    {
        if ($id != 0) {
            $exist = User::find($id);
            if (!$exist) return error('用户不存在');
        } else {
            $id = $this->uid;
        }
        $list = ModelArticle::with(['category' => function ($query) {
            $query->field('id,cate_name');
        }])->where(['user_id' => $id]);
        if ($this->uid == $id) {
            $list->order('status asc ,id desc');
        } else {
            $list->where(['status' => 1])->order('id desc');
        }
        $list = $list->hidden(['hide_content'])->paginate(10);
        $name = $id == 0 ? '用户文章列表' : '查看别人文章列表';
        LogService::record(
            user_id: getUid(),
            name: $name,
            target_id: $id
        );
        return success($list);
    }
    public function read($id)
    {
        $art = ModelArticle::with(['category' => function ($query) {
            $query->field('id,cate_name');
        }, 'userInfo' => function ($query) {
            $query->field('id,nickname,avator,signature');
        }])->hidden(['delete_time'])->where(['id' => $id])->find();
        if (!$art) return error('文章不存在或已被删除');
        if ($art['user_id'] != $this->uid) {
            if ($art['status'] == 0) return error('文章待审核');
        }
        if ($art['status'] == 2) return error('文章已被锁定，无法查看');
        $cate = Db::name('category')->where(['id' => $art['cate_id']])->find();
        if ($cate) {
            $parentCate = Db::name('category')->where(['id' => $cate['pid']])->find();
            if ($parentCate['status'] == 0) return error('当前分类已关闭，请稍后再来查看');
            if (Category::checkPrivate($cate['pid']) && empty($this->uid)) return error('文章为私密板块，请登录再来操作', 210);
        }
        $hasFollow = Db::name('follow')->where(['user_id' => $this->uid, 'follow_id' => $art['user_id'], 'relation_type' => 1, 'delete_time' => 0])->find();
        $art['is_followed'] = $hasFollow ? 1 : 0;

        $hasPayed = $this->handelPay($art);
        $hide = $this->handelHideContent($art, $hasPayed);
        $art['hide_content'] = $hide;
        // 判断是否已付费文章
        $art['is_payed'] = $hasPayed ? 1 : 0;
        // 是否已收藏该文章
        $art['is_collected'] = ArtCollect::hasCollect($id) ? 1 : 0;
        // $art['images'] = checkImg($art['images']) ?? [];
        //    更新热度
        Db::name('article')->where(['id' => $id, 'status' => 1])->inc('heat', 1)->update();
        LogService::record(
            user_id: getUid(),
            name: '文章阅读',
            target_id: $id
        );
        return success($art);
    }
    //  处理支付判断
    public function handelPay($art)
    {
        if ($art['user_id'] != $this->uid) {
            $hasPayed = Db::name('payedArt')->where(['art_id' => $art['id'], 'user_id' => $this->uid])->find();
            return $hasPayed;
        } else {
            return true;
        }
    }
    // 处理隐藏内容
    public function handelHideContent($art, $hasPayed = false)
    {
        if ($this->uid != $art['user_id']) {
            $hasPayed = Db::name('payedArt')->where(['art_id' => $art['id'], 'user_id' => $this->uid])->find();
            if ($art['type'] == 2) {
                if (!$hasPayed) return '隐藏内容需付费查看';
            }
            if ($art['type'] == 3) {
                if (!$hasPayed) return '游客无权查看，回复文章即可查看';
            }
        }
        return $art['hide_content'];
    }
    // 付费文章
    public function pay($id)
    {
        $recordLog = function ($status, $message = '') use ($id) {
            LogService::record(
                name: '文章付费',
                user_id: getUid(),
                target_id: $id,
                status: $status,
                content: $message == '' ? [] : ['reason' => $message],
            );
        };
        // 查询文章信息
        $art = ModelArticle::where(['id' => $id, 'status' => 1])->find();
        if (!$art) {
            return error('文章不存在');
        }

        // 仅对付费文章处理
        if ($art['type'] == 2) {
            $user = User::where(['id' => $this->uid])->find();
            $score = $user['score'] - $art['score'];

            // 检查用户积分是否足够
            if ($score < 0) {
                $recordLog(0, "积分不足，还差 " . abs($score) . ' 积分');
                return error("积分不足，还差 " . abs($score) . ' 积分');
            }

            // 检查是否已经支付过
            $hasPayed = Db::name('payedArt')->where(['user_id' => $this->uid, 'art_id' => $id])->find();
            if (!$hasPayed) {
                // 记录支付关系
                Db::name('payedArt')->insert(['user_id' => $this->uid, 'art_id' => $id]);
                // 分润比例（80%给作者，20%给平台）
                $authorScore = $art['score'] * 0.8;
                $platformScore = $art['score'] * 0.2;

                Db::startTrans();
                try {
                    // 扣除购买者积分
                    Db::table('gn_user')
                        ->where('id', $this->uid)
                        ->dec('score', $art['score'])
                        ->update();

                    // 检查作者是否存在
                    $author = User::where('id', $art['user_id'])->find();
                    if ($author) {
                        // 增加作者积分
                        Db::table('gn_user')
                            ->where('id', $art['user_id'])
                            ->inc('score', $authorScore)
                            ->update();

                        // 记录作者积分变动日志
                        ScoreLog::add(
                            $art['user_id'],
                            $authorScore,
                            'article_income',
                            '文章收益',
                            '文章标题《' . $art['title'] . '》'
                        );
                    } else {
                        // 记录作者不存在的日志
                        Log::warning('作者不存在，跳过积分增加：文章ID=' . $art['id'] . '，作者ID=' . $art['user_id']);
                    }

                    // 记录购买者积分变动日志
                    ScoreLog::reduce(
                        $this->uid,
                        $art['score'],
                        'article_pay',
                        '购买文章',
                        '购买文章：' . $art['title']
                    );
                    $recordLog(1);
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return error('支付失败，请重新尝试');
                }
                return success();
            }
        }
    }
    public function add()
    {
        $param = input();
        $param['content'] = remove_xss($param['content']);
        $param['user_id'] = $this->uid;
        $res = ModelArticle::create($param);
        if ($res) {
            LogService::record(
                user_id: getUid(),
                name: '发布文章',
                content: $param
            );
            return success();
        } else {
            LogService::record(
                user_id: getUid(),
                name: '发布文章',
                content: $param,
                status: 0
            );
            return error();
        }
    }
    public function edit()
    {
        $param = input();
        if (!empty($param['images'])) {
            $param['images'] = checkImg($param['images']);
        }
        $res = ModelArticle::update($param);
        if ($res) {
            LogService::record(
                user_id: getUid(),
                name: '编辑文章',
                content: ['original_data' => $param],
                target_id: $param['id']
            );
            return success();
        } else {
            LogService::record(
                user_id: getUid(),
                name: '编辑文章',
                status: 0,
                target_id: $param['id']
            );
            return error();
        }
    }
    // 上传图片
    public function uploadImg()
    {
        $file =  request()->file();
        if (!$file) {
            return error('请上传jpg,png,jpeg后缀图片');
        }
        try {
            validate(['file' => 'fileSize:5242880|fileExt:jpg,png,jpeg'])
                ->check($file);
            if (empty($file)) return error();
            $images = \think\facade\Filesystem::disk('images')->putFile('article', $file['file']);
            if (!$images) return error('图片上传失败');
            $images = '/static/images/' . str_replace('\\', '/', $images);
            Db::name('files')->insert([
                'user_id' => $this->uid,
                'desc' => '文章图片',
                'route_path' => request()->controller() . '/' . request()->action(),
                'file_name' => $file['file']->getFilename(),
                'file_path' => $images,
                'size' => $file['file']->getSize(),
                'create_time' => time()
            ]);
            return success(['src' => $images]);
        } catch (\think\exception\ValidateException $e) {
            return error($e->getMessage());
        }
        LogService::record(
            user_id: getUid(),
            name: '上传文章图片',
        );
    }
    public function del()
    {
        $id = input('id');
        $recordLog = function ($status, $message = '') use ($id) {
            LogService::record(
                name: '删除文章',
                user_id: getUid(),
                target_id: $id,
                status: $status,
                content: $message == '' ? [] : ['reason' => $message],
            );
        };
        if (!$id) {
            $recordLog(0, '文章ID不能为空');
            return error('文章ID不能为空');
        }
        $hasArt = ModelArticle::where(['id' => $id, 'user_id' => $this->uid]);
        if ($hasArt->findOrEmpty()->isEmpty()) {
            $recordLog(0, '文章不存在或已被删除');
            return error('文章不存在或已被删除');
        }
        $res = ModelArticle::destroy($id);
        if ($res) {
            $recordLog(1);
            return success();
        }
        $recordLog(0);
        return error();
    }
    // 我的收藏 | Ta的收藏
    public function myCollect($id = null)
    {
        $id = $id ?? $this->uid;
        $exist = User::find($id);
        if (!$exist) return error('用户不存在');
        $list = ArtCollect::alias('c')->join('article a', 'a.id = c.art_id')->where('c.user_id', $id)->paginate();
        $name = $id == 0 ? '用户收藏' : '查看别人收藏';
        LogService::record(
            user_id: getUid(),
            name: $name,
            target_id: $id
        );
        return success($list);
    }
    // 收藏文章
    public function collect()
    {
        // 获取当前用户ID和文章ID
        $userId = $this->uid;
        $articleId = input('id');
        $recordLog = function ($status, $message = '') use ($articleId) {
            LogService::record(
                name: '收藏|取消收藏文章',
                user_id: getUid(),
                target_id: $articleId,
                status: $status,
                content: $message == '' ? [] : ['reason' => $message],
            );
        };
        // 判断参数是否合法
        if (empty($userId) || empty($articleId)) {
            $recordLog(0, '请求异常：缺少参数');
            return error('请求异常', 201);
        }

        // 查询用户的收藏记录（包括已软删除的记录）
        $collection = Db::name('artCollect')
            ->where('delete_time', 0)  // 只查询未删除的记录
            ->where([
                'user_id' => $userId,
                'art_id' => $articleId
            ])
            ->find();

        // 查询被软删除的记录
        $deletedCollection = Db::name('artCollect')
            ->where('delete_time', 0)  // 查询已删除的记录
            ->where([
                'user_id' => $userId,
                'art_id' => $articleId
            ])
            ->find();
        // 处理不同情况
        if ($collection) {
            // 如果存在未删除的收藏记录，执行软删除
            $result = Db::name('artCollect')
                ->where([
                    'user_id' => $userId,
                    'art_id' => $articleId
                ])
                ->update([
                    'delete_time' => time()
                ]);
            if ($result) {
                $recordLog(1);
                return success();
            }
            $recordLog(0);
            return error('取消收藏失败');
        } elseif ($deletedCollection) {
            // 如果存在已删除的收藏记录，恢复记录
            $result = Db::name('artCollect')
                ->where([
                    'user_id' => $userId,
                    'art_id' => $articleId
                ])
                ->update([
                    'delete_time' => 0,
                ]);
            if ($result) {
                $recordLog(1);
                return success();
            }
            $recordLog(0);
            return error('收藏失败');
        } else {
            // 如果不存在任何记录，创建新记录
            $result = Db::name('artCollect')
                ->insert([
                    'user_id' => $userId,
                    'art_id' => $articleId,
                    'create_time' => time(),
                    'delete_time' => 0
                ]);

            if ($result) {
                $recordLog(1);
                return success();
            }
            $recordLog(0);
            return error('收藏失败');
        }
    }
}
